package com.robusta.app.web.controller;

import com.google.common.base.Function;
import com.robusta.app.api.AvailableTemplates;
import com.robusta.app.domain.spreadsheet.templates.Metadata;
import com.robusta.app.web.model.UploadViewModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static com.google.common.collect.Lists.transform;

@Controller
@RequestMapping("home")
public class HomePageController {
    private AvailableTemplates availableTemplates;

    @Autowired
    public HomePageController(AvailableTemplates availableTemplates) {
        this.availableTemplates = availableTemplates;
    }

    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.GET)
    public String displayHomePage(ModelMap modelMap) {
        modelMap.addAttribute("uploadModel", new UploadViewModel());
        return "home";
    }

    @ModelAttribute("availableTemplates")
    public List<String> availableTemplates() {
        return transform(availableTemplates.lookup(), toTemplateNames());
    }

    private Function<Metadata, String> toTemplateNames() {
        return new Function<Metadata, String>() {
            @Override
            public String apply(Metadata input) {
                return input.templateName();
            }
        };
    }

}
